package cn.car.utils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class CarTimeUtil {

    public static final String DAY_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 字符串根据某个转换字符串转换为时间戳
     *
     * @param dateStr 时间字符串
     * @param pattern 转换字符串
     * @return 转换后的时间戳
     */
    public static long strToTimestamp(String dateStr, String pattern) {
        if (null == pattern || pattern.isEmpty()) {
            pattern = DAY_TIME_FORMAT;
        }
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        final LocalDateTime date;

        if (dateStr.length() > 10) {
            date = LocalDateTime.parse(dateStr, formatter);
        } else {
            date = LocalDate.parse(dateStr, formatter).atStartOfDay();
        }

        final ZoneId zoneId = ZoneId.systemDefault();
        final ZonedDateTime zdt = date.atZone(zoneId);
        return zdt.toInstant().toEpochMilli();
    }
}
